package com.ruoyi.SuveryInterface.SuveryUtils.util;

import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;

public class Sign {
    private static final String CONTENT_CHARSET = "UTF-8";

    public Sign() {
    }

    public static String createSign(Map<Object, Object> parameters, String uri, String secret) throws Exception {
        SortedMap<Object, Object> parametersForSign = new TreeMap();
        parametersForSign.put("uri", uri);
        parametersForSign.putAll(parameters);
        StringBuilder sb = new StringBuilder();
        Set es = parametersForSign.entrySet();
        Iterator it = es.iterator();

        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"sign".equals(k) && !"key".equals(k)) {
                if (!it.hasNext()) {
                    sb.append(k).append("=").append(v);
                } else {
                    sb.append(k).append("=").append(v).append("&");
                }
            }
        }

        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes("UTF-8"), mac.getAlgorithm());
        mac.init(secretKey);
        byte[] hash = mac.doFinal(sb.toString().getBytes("UTF-8"));
        return (new BASE64Encoder()).encode(hash);
    }
}
